package com.bcinfo.iccard.busi.handler;

import java.util.UUID;
import org.apache.commons.lang3.exception.ExceptionUtils;
import com.bcinfo.iccard.busi.AbstractBusinessHandler;
import com.bcinfo.iccard.enums.Constants;
import com.bcinfo.iccard.exception.IccardDatabaseException;
import com.bcinfo.iccard.exception.IccardException;
import com.bcinfo.iccard.model.Pos;
import com.bcinfo.iccard.util.DataCryptor;
import com.solab.iso8583.IsoMessage;
import com.solab.iso8583.IsoType;
/**
 * 签到处理
 * @author wangguangchun
 *
 */
public class SignUpHandler extends AbstractBusinessHandler {
	
	@Override
	public void handleBusiness(IsoMessage req, IsoMessage resp)
			throws Exception {
		if(req==null ||resp==null){
			throw new IccardException("iso message req or resp is null,discard this request!");
		}
		
		if(_logger.isDebugEnabled()){
			_logger.debug("handleBusiness:"+req.toString());
		}
		try
        {
		    resp.copyFieldsFrom(req, 3,11,41);
		    Pos pos=getPos(req);
            String pinKey=UUID.randomUUID().toString().replaceAll("-","").substring(16);
            String macKey=UUID.randomUUID().toString().replaceAll("-","").substring(16);
            _logger.debug("generate pinKey:"+pinKey+",macKey:"+macKey);
            //主密钥为长度16的 8位16进制表示的字符串
            String primaryKey=pos.getPmk();
            if(primaryKey==null ||primaryKey.length()%8!=0 ||primaryKey.length()<16){
                _logger.warn("the primaryKey["+primaryKey+"] of pos["+pos.getPosCode()+"] is incorrect,use default set["+Constants.SYS_PRI_KEY+"]");
                primaryKey=getConfig(Constants.SYS_PRI_KEY);
                pos.setPmk(primaryKey);
            }
            pos.setPik(pinKey);
            pos.setMak(macKey);
            posService.update(pos);
            String m1CardReadKey=getConfig(Constants.SYS_M1_READ_KEY);
            //单DES加密,DES(pinKey,PK)+DES(macKey,PK)+DES(m1CardReadKey,PK)
            String encryptWorkKey =DataCryptor.encryption(pinKey, primaryKey)+DataCryptor.encryption(macKey, primaryKey)+DataCryptor.encryption(m1CardReadKey, primaryKey);
            resp.setValue(48, encryptWorkKey, IsoType.LLLVAR, 0);
            resp.setValue(39,Constants.ResponeCode.approval.value , IsoType.ALPHA, 2);
        }
        catch (IccardDatabaseException e)
        {
            _logger.error(ExceptionUtils.getStackTrace(e));
            resp.setValue(39,Constants.ResponeCode.timeOut.value , IsoType.ALPHA, 2);
        }
	}

	/* (non-Javadoc)
	 * Description: <br/> 
	 *
	 * @param req
	 * @return 
	 * @see com.bcinfo.iccard.busi.AbstractBusinessHandler#authenticate(com.solab.iso8583.IsoMessage)
	 */
	@Override
	protected boolean authenticate(IsoMessage req,String macKey)
	{
	    _logger.debug("skip mac authentication while handing signUp req.");
	    return true;
	}
}
